package gae.colopl.servlet;

import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

    private static final Logger logger = Logger.getLogger(LoginFilter.class.getName());
    
    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain arg2) throws IOException, ServletException {
        
        HttpSession session = ((HttpServletRequest)req).getSession(false);
        String reqUri = ((HttpServletRequest)req).getRequestURI();
        if (reqUri.contains("update.do")) {
            
        }
        else if (!reqUri.contains("login.do")) {
            if (session == null) {
                session = ((HttpServletRequest)req).getSession(true);
                ((HttpServletResponse)res).sendRedirect("/do/login.do");
            } else {
                Boolean isLoggedIn = (Boolean)session.getAttribute("isLoggedIn");
                if (isLoggedIn == null || isLoggedIn != null & isLoggedIn == false) {
                    ((HttpServletResponse)res).sendRedirect("/do/login.do");
                }
//                Enumeration enu = session.getAttributeNames();
//                while (enu.hasMoreElements()) {
//                    logger.severe("before: " + enu.nextElement().toString());
//                }
            }
        }
        
        arg2.doFilter(req, res);
        
//        if (session != null) {
//            Enumeration enu = session.getAttributeNames();
//            while (enu.hasMoreElements()) {
//                logger.severe("after: " + enu.nextElement().toString());
//            }
//        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
